package com.kb.controller.interceptor;

import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.kb.annotation.UserLoginToken;
import com.kb.common.MeException;
import com.kb.util.TokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class LoginrequiredInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");

        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();

            if (method.isAnnotationPresent(UserLoginToken.class)) {
                UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);

                if(userLoginToken.required()){
                    if(token == null){
                        throw new MeException("token为空，请重新登录");
                    }else{
                        //查询用户是否存在
                        // 验证token
                        try {
                            TokenUtil.verify(token);
                        } catch (Exception e) {
                            if (e instanceof TokenExpiredException || e instanceof InvalidClaimException) {
                                // 触发刷新AccessToken的操作
                                throw new MeException("登录令牌鉴权失败，令牌超时");
                            } else {
                                // 签名失效的场景
                                throw new MeException("登录令牌鉴权失败，" + e.getMessage());
                            }
                        }
                        return  true;
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
}
